package com.anlu.concurrent.ch2.forkjoin.test;

import java.util.Random;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
import java.util.concurrent.RecursiveTask;

/**
 * <p>
 * Description:TODO 详细描述
 * <p>
 * Copyright: 天津联想协同科技有限公司
 * <p>
 *
 * @author anlu
 * @date 2021/9/6 18:01
 */
public class RecusiveTaskDemmo extends RecursiveTask<Integer> {

    // 每个小任务最多只能 打印70个数
    private static final int MAX = 70;
    private  int arr[];
    private int start;
    private int end;

    public RecusiveTaskDemmo(int[] arr, int start, int end) {
        this.arr = arr;
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        int sum = 0;
        //当end-start 的值小于Max的时候，开始打印
        if(end-start<MAX){
            for (int i=start;i<end;i++){
                sum+=arr[i];
            }
            return sum;
        }else{
            System.out.println("任务分解");
            //将大任务分解成两个小任务
            int middle = (start+end)/2;
            RecusiveTaskDemmo left = new RecusiveTaskDemmo(arr,start,middle);
            RecusiveTaskDemmo right= new RecusiveTaskDemmo(arr,middle,end);

            //并行执行两个小任务
            left.fork();
            right.fork();
            //把两个小任务的累加的结果合并起来;
            return left.join()+right.join();
        }
    }

    public static void main(String[] args) {
        int arr[] = new int[1000];
        Random random = new Random();
        int total = 0;
        //初始化100个元素
        for (int i=0;i<arr.length;i++){
            int temp = random.nextInt(100);
            //对数组元素进行赋值，并将数组元素的值添加到total总和中
            total += (arr[i]=temp);
        }
        System.out.println("初始化总和为："+total);

        //创建包含
        ForkJoinPool pool = new ForkJoinPool();
        Integer result = pool.invoke(new RecusiveTaskDemmo(arr,0,arr.length-1));
        System.out.println("计算的结果是："+result);

        //关闭线程池
        pool.shutdown();
    }
}
